<template>
	<view>
		<view class="map_container">
			<view class="search">
				<u-search placeholder="请精确输入搜索内容" v-model="keyword" @custom="bindInput" @search="bindInput"></u-search>
				<u-popup :show="show" mode="top" customStyle="positon:absolute;top:100rpx">
					<view class="content">
						<scroll-view scroll-y="true" style="">
							<view>
								<view v-for="(i ,index) in tips" :key="index"
									style="padding: 30rpx;border-bottom: .5px solid #E2E2E2" @click="goSearch(i)">
									{{i.name}}
								</view>
							</view>
						</scroll-view>
					</view>
				</u-popup>
			</view>

			<map id="myMap" class="map" style="width: 100%; height: 90%;" :latitude="latitude" :longitude="longitude"
				:markers="markers" show-location @poitap="poitap"></map>
		</view>
		<view class="location">
			<text class="local">{{local}}</text>
			<text class="distance" v-if="range!==''">(距离你{{range}})</text>
			<u-button text="确定" @click="goback()"></u-button>
		</view>
	</view>
</template>

<script>
	import amapFile from "@/libs/amap-wx.130.js";
	var self, mapCtx
	export default {
		data() {
			return {
				key: '0a7e3109fe2a9b39a5e2b854e164614f',
				latitude: '',
				longitude: '',
				firstlat: '',
				firstlng: '',
				local: '',
				distance: '',
				// 标记点
				markers: [],
				range: '',
				circles: [],
				radius: 0,
				amapObject: null,
				keyword: '',
				tips: [],
				show: false
			}
		},
		onLoad() {
			self = this
			mapCtx = wx.createMapContext('myMap')
			self.getAuthorizeInfo()
			// self.getLocationInfo()
			// var amaFile = require('../../libs/amap-wx.130.js')
			//2XXBZ-D63C4-FDHU6-XQACW-H56O6-DRBDC
			this.amapObject = new amapFile.AMapWX({
				key: '0a7e3109fe2a9b39a5e2b854e164614f'
			})
		},
		methods: {
			goSearch(e) {
				console.log(e)
				let arr = e.location.split(',')
				this.latitude = Number(arr[1])
				this.longitude = Number(arr[0])
				console.log(arr, this.latitude)
				this.keyword = e.name
				this.local = this.keyword
				this.show = false;
			},
			bindInput: function() {
				let that = this
				var keywords = this.keyword;
				this.amapObject = new amapFile.AMapWX({
					key: '0a7e3109fe2a9b39a5e2b854e164614f'
				})
				this.amapObject.getInputtips({
					keywords: keywords,
					location: '',
					success: function(data) {
						if (data && data.tips) {
							let arr = []
							for (let i = 0; i < data.tips.length; i++) {
								if (data.tips[i].location.length != 0) {
									arr.push(data.tips[i])
								}
							}
							that.tips = arr
							that.show = true;
						}
					}
				})
			},
			// 位置授权
			getAuthorizeInfo() {
				let self = this
				uni.getFuzzyLocation({
					type: 'wgs84',
					success(res) {
						console.log("这是您的位置信息", res);
						self.latitude = res.latitude
						self.longitude = res.longitude
						self.firstlat = res.latitude,
						self.firstlng = res.longitude
						let val = `${res.longitude},${res.latitude}`
						self.getLocationInfo(val)
					},
					fail: (info) => {
						console.log('错误1' + info)
						self.openAuthSetting()
					}
				})
				// uni.authorize({
				// 	scope: 'scope.userLocation',
				// 	success() { // 允许授权
				// 		uni.getLocation({
				// 			success: function(res) {
				// 				console.log("经纬度", res);
				// 				self.latitude = res.latitude
				// 				self.longitude = res.longitude
				// 				self.firstlat = res.latitude,
				// 				self.firstlng = res.longitude
				// 			},
				// 		})
				// 	},
				// 	fail() { // 拒绝授权
				// 		this.openConfirm();
				// 		console.log("你拒绝了授权，无法获得周边信息")
				// 	}
				// })
			},
			openAuthSetting() {
				let that = this;
				uni.getSetting({
					success: (res) => {
						console.log(res, JSON.stringify(res, "getSetting"));
						if (
							res.authSetting["scope.userFuzzyLocation"] != undefined &&
							res.authSetting["scope.userFuzzyLocation"] != true
						) {
							uni.showModal({
								title: "请求授权当前位置",
								content: "需要获取您的地理位置，请确认授权",
								success: function(res) {
									if (res.cancel) {
										uni.showToast({
											title: "拒绝授权",
											icon: "none"
										});
									} else if (res.confirm) {
										uni.openSetting({
											success: function(dataAu) {
												console.log(dataAu, "openSetting");
												if (dataAu.authSetting[
														"scope.userFuzzyLocation"] ==
													true) {
													uni.showToast({
														title: "授权成功",
														icon: "none"
													});
													//再次授权，调用wx.getLocation的API
													that.getAuthorizeInfo();
												} else {
													uni.showToast({
														title: "授权失败",
														icon: "none"
													});
												}
											},
										});
									}
								},
							});
						} else if (res.authSetting["scope.userFuzzyLocation"] == undefined) {
							//调用wx.getLocation的API
							console.log("首次授权");
							this.getAuthorizeInfo();
						} else {
							//调用wx.getLocation的API
							this.getAuthorizeInfo();
						}
					},
				})
			},
			// 获取地理位置
			getLocationInfo(val) {
				var that = this;
				this.amapObject = new amapFile.AMapWX({
					key: '0a7e3109fe2a9b39a5e2b854e164614f'
				})
				let location = ''
				if (val) {
					location = val
				} else {
					location = ''
				}
				// console.log(val)
				this.amapObject.getRegeo({
					iconPath: "",
					location: location,
					success: (res) => {
						// debugger
						console.log(res)
						// 移动到当前位置
						that.toLocation(res)
						that.latitude = res[0].latitude;
						that.longitude = res[0].longitude;
						console.log(res)
						// that.local = res[0].regeocodeData.formatted_address
						that.local = res[0].name
						that.markers = [{
								id: 1,
								latitude: res[0].latitude,
								longitude: res[0].longitude,
								iconPath: res[0].iconPath,
								name: 'map',
								width: 12,
								height: 20,
							}],
							// 地图半径画圆
							this.circles = [{
								latitude: res[0].latitude,
								longitude: res[0].longitude,
								fillColor: "rgba(255,42,65,0.08)",
								color: "#FF0000",
								radius: 50,
							}]
					},
					fail: (err) => {
						console.log(err)
					}
				})
			},
			toLocation(obj) {
				// 改变地图中心位置
				console.log(obj)
				mapCtx.moveToLocation(obj)
				// 移动标记点并添加动画效果
				mapCtx.translateMarker({
					markerId: 1,
					autoRotate: false,
					duration: 100,
					destination: {
						latitude: obj.latitude,
						longitude: obj.longitude,
					},
					animationEnd() {
						console.log('animation end')
					}
				})
			},
			poitap: function(e) {
				console.log(e, "poitap")
				var obj = e.detail
				self.toLocation(obj)
				console.log(e.detail.name)
				this.local = e.detail.name
				console.log(this.latitude, this.longitude)
				this.latitude = e.detail.latitude
				this.longitude = e.detail.longitude
				return false;
				var distance = this.getDistance(this.firstlat, this.firstlng, e.detail.latitude, e.detail.longitude)
				let points = [this.longitude, this.latitude];
				this.getLocationInfo(points)
				distance = parseInt(distance * 1000);
				if (distance != null && distance > 0) {
					this.range = distance + "米";
					if (distance >= 1000) {
						this.range = (Math.round(distance / 100) / 10).toFixed(1) + "公里";
					}
				}
			},
			getAddress(points) {

			},
			goback() {
				// console.log(this.local)
				// uni.setStorageSync('local', this.local)
				let e = {
					local: this.local,
					latitude: this.latitude,
					longitude: this.longitude,
				}
				uni.$emit('map', e)
				uni.navigateBack()
			},
			// 计算距离
			getDistance: function(lat1, lon1, lat2, lon2) {
				var EARTH_RADIUS = 6378.137; //地球半径
				var radLat1 = lat1 * Math.PI / 180.0;
				var radLat2 = lat2 * Math.PI / 180.0;
				var radlon1 = lon1 * Math.PI / 180.0;
				var radlon2 = lon2 * Math.PI / 180.0;
				this.latitude = lat2
				this.longitude = lon2
				//差值
				var vLat = radLat1 - radLat2;
				var vLon = radlon1 - radlon2;
				//s就是一个球体上的切面，它的圆心即是球心的一个周长最大的圆。
				var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(vLat / 2), 2) +
					Math.cos(radLat1) * Math.cos(radLat2) *
					Math.pow(Math.sin(vLon / 2), 2)));
				s = s * EARTH_RADIUS;
				var distance = Math.round(s * 10000) / 10000;
				return distance;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.map_container {
		width: 100%;
		overflow: hidden;
		position: absolute;
		top: 0;
		bottom: 80px;
		left: 0;
		right: 0;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;

		.search {
			width: 90%;
			padding-bottom: 15rpx;
		}

		.map {
			height: auto;
			width: 100%;
		}
	}

	.location {
		width: 95%;
		height: auto;
		position: absolute;
		left: 0;
		right: 0;
		bottom: 0px;
		// height: 80px;
		background: #fff;
		padding: 2.5%;
		overflow: hidden;

		.distance {
			color: #4295FA;
			font-size: 12px;
		}
	}
</style>
